package com.example.index.ui

import android.annotation.SuppressLint
import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import androidx.recyclerview.widget.RecyclerView

class SheetLayoutManager : RecyclerView.LayoutManager() {

    var currPosition: Int = 0

    var scrollOffset: Int = 0

    var secondaryScale = 0.8f

    var space = 0

    var itemWidth = 0
    var itemHeight = 0

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {

        //每一次的 layoutChildren 都代表布局失效，需要重新 排布
        detachAndScrapAttachedViews(recycler)

        if (itemCount <= 0) return

        val firstChild = recycler.getViewForPosition(0)
        measureChildWithMargins(firstChild, 0, 0)
        itemWidth = firstChild.measuredWidth
        itemHeight = firstChild.measuredHeight

        //layout views
        fill(recycler, 0)

    }


    fun fill(recycler: RecyclerView.Recycler, dx: Int): Int {

        //dx >0  左滑 ， dx<0
        if (scrollOffset + dx < 0) return 0

        scrollOffset += dx
        Log.i(TAG, "scrollHorizontallyBy: ${dx} $scrollOffset")

        detachAndScrapAttachedViews(recycler)
        //如果滚动过，那么从前一个 view 开始布局

        //recycle view
        val count = childCount
        for (i in 0 until count) {
            val view = getChildAt(i)
            if (view != null && (view.left < 0 || view.left > width))
                removeAndRecycleView(view, recycler)
        }

        val currPos = scrollOffset / (itemWidth + space)

        val offset = scrollOffset % (itemWidth + space)


        val start = if (currPos > 0) currPos - 1 else 0


        for (i in start until itemCount) {

            if (i != currPos) {

                val child = recycler.getViewForPosition(i)
                addView(child)
                measureChildWithMargins(child, 0, 0)

                val left = (width - itemWidth) / 2 + (i - currPos) * (itemWidth + space) - offset

                val top = (height - itemHeight) / 2

                val scaleY = 0.8f

                child.layout(left, top, left + itemWidth, top + itemHeight)
            }

        }


        //layout base item

        val baseChild = recycler.getViewForPosition(currPos)

        addView(baseChild)
        measureChildWithMargins(baseChild, 0, 0)

        val left = (width - itemWidth) / 2 - offset

        val top = (height - itemHeight) / 2


        val currScaleY = 1f

        baseChild.layout(left, top, left + itemWidth, top + itemHeight)

        return dx
    }


    val TAG = "SheetLayoutManager"
    override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State?): Int {
        //滑动情况下直接根据锚点信息排布即可，这里的锚点信息即 当前 中心位置显示的 view 以及滑动距离

        return fill(recycler, dx)
    }

    override fun canScrollHorizontally(): Boolean {
        return true
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onAttachedToWindow(view: RecyclerView?) {
        super.onAttachedToWindow(view)

//        view?.setOnTouchListener { v, event ->
//
//
//
//
//            return@setOnTouchListener true
//        }
    }


    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(-2, -2)
    }


    override fun onSaveInstanceState(): Parcelable? {

        val saveState = SaveState()

        saveState.coordinatePosition = currPosition
        saveState.coordinateOffset = scrollOffset
        return saveState
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        super.onRestoreInstanceState(state)
        val saveState = state as SaveState
        currPosition = saveState.coordinatePosition
        scrollOffset = saveState.coordinateOffset
    }


    class SaveState() : Parcelable {

        var coordinatePosition: Int = 0
        var coordinateOffset: Int = 0

        constructor(parcel: Parcel) : this() {
            coordinatePosition = parcel.readInt()
            coordinateOffset = parcel.readInt()
        }

        override fun writeToParcel(parcel: Parcel, flags: Int) {
            parcel.writeInt(coordinatePosition)
            parcel.writeInt(coordinateOffset)
        }

        override fun describeContents(): Int {
            return 0
        }

        companion object CREATOR : Parcelable.Creator<SaveState> {
            override fun createFromParcel(parcel: Parcel): SaveState {
                return SaveState(parcel)
            }

            override fun newArray(size: Int): Array<SaveState?> {
                return arrayOfNulls(size)
            }
        }


    }
}